<?php

namespace app\admin\controller;
use app\admin\middleware\Auth;
use app\model\ExpressBizId;
use app\model\ExpressBizIdModel;
use app\model\ExpressModel;
use app\model\ExpressServiceModel;
use app\model\OrderLogisticsModel;
use app\model\OrdersModel;
use app\model\RedisModel;
use GuzzleHttp\Client;
use think\App;


class Wx extends Base {

    protected $middleware = [Auth::class];
    private $aid;
    private $req;
    private $expressModel;

    private $expressBizModel;

    public $cacheKey = "delivery:id:";

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->aid = $this->isLogin();

        if(!$this->aid){
            return $this->noLogin();
        }

        $this->req = request()->param();

        $this->expressModel = new ExpressModel();

        $this->expressBizModel = new ExpressBizIdModel();
    }


    /*
  * 获取快递公司列表
  *
  * */
    public function getLogistic(){

        if(!isset($this->req["waybill_ids"]) || empty($this->req["waybill_ids"])){
            return $this->fail("缺少参数：waybill_ids");
        }

        $return=[];
        $orderLogisticsModel = new OrderLogisticsModel();
        foreach ($this->req["waybill_ids"] as $waybill_id){
            $where=[];
            $where["waybill_id"] = $waybill_id;
            $list = $orderLogisticsModel->getList($where);
            $orderInfo = (new OrdersModel())->getInfo($list[0]['order_id']);
            $token = $orderInfo["userInfo"]["wx_openid"];

            try {
                $response = getLogistics($token, $waybill_id, $list[0]["wx_request"]["delivery_id"]);
            }catch (\Exception $e){
                return $this->fail("网络异常：".$e->getMessage());
            }

            // 处理响应
            if ($response->getStatusCode() == 200) {
                $data = $response->getBody()->getContents();
                $data = json_decode($data, true);
                $data["path_item_list"] = array_reverse($data["path_item_list"]);
                if(isset($data['errcode'])){
                    return $this->fail("请求轨迹接口错误：错误码->".$data['errcode'].",错误信息->".$data['errmsg']);
                }
                $return[] = $data;
            } else {
                return $this->fail("请求腾讯快递接口失败：". $response->getBody()->getContents());
            }

        }
        return  $this->succData(count($this->req["waybill_ids"]),$return);
    }


    /*
     * 绑定&解绑物流合作商
     * */
    public function bindExpressAccount(){

        if(!$this->req["type"] || !in_array($this->req["type"],["bind","unbind"])){
            return $this->fail("请选择操作是绑定还是解绑");
        }
        if(!$this->req["delivery_id"]){
            return $this->fail("请选择快递公司");
        }
        if(!$this->req["biz_id"]){
            return $this->fail("请输入绑定的快递账号");
        }
        if(!$this->req["password"]){
            return $this->fail("请输入绑定的快递账号密码");
        }

        if(!$this->req["password"]){
            return $this->fail("请输入绑定的快递账号密码");
        }

        if($this->req["delivery_id"] == "EMS" && (!isset($this->req["remark_content"]) || empty($this->req["remark_content"])) ){
            return $this->fail("EMS 快递必须填写备注内容，格式为：电话：xxxxx 联系人：xxxxx 服务类型：xxxxx 发货地址：xxxx");
        }

        $response = bindExpressAccount($this->req["type"],$this->req["delivery_id"],$this->req["biz_id"],$this->req["password"],$this->req["remark_content"]);

        if ($response->getStatusCode() == 200) {
            $data = $response->getBody()->getContents();
            $data = json_decode($data, true);

            if($data['errcode'] == 0){
                $this->succ("","操作成功");
            }else{
                return $this->fail("操作失败:".$data["errmsg"]);
            }

        } else {
            return $this->fail("请求腾讯快递接口失败：". $response->getBody()->getContents());
        }

    }



    /*
     * 获取快递公司列表
     *
     * */
    public function getExpressList(){

        $where=[];
        $where["delivery_status"] = 1;
        $total = $this->expressModel->getTotal($where);
        $list = $this->expressModel->getList($where);

        return $this->succData($total,$list);

//        $response =getExpressList();
//        // 处理响应
//        if ($response->getStatusCode() == 200) {
//            $data = $response->getBody()->getContents();
//            $data = json_decode($data, true);
//
//            //更新数据
//            $express = new ExpressModel();
//            $expressService = new ExpressServiceModel();
//            foreach ($data["data"] as $one){
//
//                $express->batchAdd([
//                    'delivery_id'=>$one["delivery_id"],
//                    'delivery_name'=>$one["delivery_name"],
//                    'can_use_cash'=>$one["can_use_cash"],
//                    'can_get_quota'=>$one["can_get_quota"],
//                ]);
//
//                foreach ($one['service_type']  as $type){
//                    $expressService->batchAdd([
//                        'delivery_id'=>$one["delivery_id"],
//                        'service_type'=>$type["service_type"],
//                        'service_name'=>$type["service_name"],
//                    ]);
//                }
//            }
//
//            return $this->succData($data["count"],$data["data"]);
//        } else {
//            return $this->fail("请求腾讯快递接口失败：". $response->getBody()->getContents());
//        }
    }


    /*
     * 获取所有绑定的物流账号
     * */

    public function getAllExpressAccount(){
         //获取绑定的账号列表
        $response =getAllExpressAccount();
        if ($response->getStatusCode() == 200) {
            $data = $response->getBody()->getContents();
            $data = json_decode($data, true);
            $expressBizId = new ExpressBizIdModel();
            $expressBizId->delAll(["is_cash"=>0]);
            foreach ($data["list"] as  &$item){
                      $expressBizId->insertGetId([
                          "delivery_id" => $item["delivery_id"],
                          "biz_id" => $item["biz_id"],
                          "biz_id_name" => $item["alias"],
                      ]);
            }

//            foreach ($data["list"] as  &$item){
//                $itemRes = getExpressAccountQuota($item["delivery_id"],$item["biz_id"]);
//                if ($itemRes->getStatusCode() == 200) {
//                    $itemResData = $itemRes->getBody()->getContents();
//                    $itemResData = json_decode($itemResData, true);
//                    if(isset($itemResData["quota_num"])){
//                        $item["quota_num"] = $itemResData["quota_num"];
//                    }else{
//                        $item["quota_num"] = "请求腾讯快递接口失败：". $itemResData["errmsg"];
//                    }
//
//                } else {
//                    $item["quota_num"] = "请求腾讯快递接口失败：". $response->getBody()->getContents();
//                }
//            }

        } else {
            return $this->fail("请求腾讯获取绑定账号接口失败：". $response->getBody()->getContents());
        }

        $where=[];
        $where["is_cash"] = isset($this->req["is_cash"]) ? $this->req["is_cash"] : 0;
        $where["biz_id_status"] = 1;
        $total = $this->expressBizModel->getTotal($where);
        $list = $this->expressBizModel->getList($where);

        return $this->succData($total,$list);

    }




    public function delCache($id)
    {
        $redisModel = new RedisModel();

        return $redisModel->delete($this->cacheKey.$id);
    }


    public function delAllCache()
    {
        $redisModel = new RedisModel();

        return $redisModel->deleteAll($this->cacheKey);
    }

}